//
//  HomeTableViewCell.swift
//  weiboxiangmu
//
//  Created by wei_jingyun on 15/7/1.
//  Copyright © 2015年 wei_jingyun. All rights reserved.
//

import UIKit
import SDWebImage

let HomeCellOne = "homeCellOne"
let HomeCellTwo = "HomeCellTwo"
/// 图片视图可重用标示符
private let JYPictureCellReuseIdentifier = "JYPictureCellReuseIdentifier"

class HomeTableViewCell: UITableViewCell , UICollectionViewDataSource{
    
    /// 配图视图宽度约束
    var widthCons: NSLayoutConstraint?
    /// 配图视图高度约束
    var heightCons: NSLayoutConstraint?
    /// 配图视图上边间隔约束
    var topCons: NSLayoutConstraint?
    
    
    // 微博数据模型
    var status:Status?{
        didSet{
            let user = status?.user
            let retweeted = status?.retweeted_status
            // 设置用户图标 会员图标 与 认证图标
            iconView.sd_setImageWithURL(NSURL(string: (user?.profile_image_url)!))
            vipIconView.image = status?.user?.mbImage
            memberIconView.image = status?.user?.verifiedImage
            
            // 用户名称 时间  来自  微博内容
            nameLabel.text = user?.name
            timeLabel.text = "刚刚"
            sourceLabel.text = status?.source == nil ? "" : "来自: \(status!.source!)"
            contentLabel.text = status?.text
            
            // 设置转发微博的文字
            if retweeted != nil {
                let st1 = retweeted?.user?.name ?? ""
                let st2 = retweeted?.text ?? ""
                forwardLabel.text = "    \(st1) \(st2)"
            }
    
            // 设置图片视图的宽高  并刷新配图视图
            let size = calcPictureViewSize(status!)
            widthCons?.constant = size.viewSize.width
            heightCons?.constant = size.viewSize.height
            pictureLayout.itemSize = size.itemSize
            
            if size.viewSize == CGSizeZero {
                topCons?.constant = 0
            }else {
                topCons?.constant = 12
                pictureView.reloadData()
            }

        }
    }
    
    //  MARK: 根据模型判断选择哪个cell
    class func StatusCellID(status: Status) -> String {
        return status.retweeted_status == nil ? HomeCellOne : HomeCellTwo
    }
    
    //  MARK: 计算并缓存行高到模型
    func rowHeight(status: Status) -> CGFloat {
        // 调用 didSet 更新图片流的约束
        self.status = status
        // 强制更新布局
        layoutIfNeeded()
        
        status.rowHeight = CGRectGetMaxY(footerView.frame)
        return status.rowHeight
    }
    
    //  MARK: 抽取pictureView 的约束提取
    func pictureViewLayoutConstraint(cons : [NSLayoutConstraint]){
        widthCons = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Width)
        heightCons = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Height)
        topCons = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Top)
    }

    
    // MARK: - pictureView 数据源方法
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { // 如果数组为空返回0
        return status?.picURLs?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(JYPictureCellReuseIdentifier, forIndexPath: indexPath) as! StatusPicturCell
        
        // 必定存在
        cell.imageURL = status!.picURLs![indexPath.row]
        return cell
    }
    
    /// 配图视图设置
    private func preparePictureView(){
        // 1. 设置背景颜色
        pictureView.backgroundColor = UIColor.lightGrayColor()
        
        // 代理
        pictureView.dataSource = self
        
        // 3.注册可从用cell
        pictureView.registerClass(StatusPicturCell.self, forCellWithReuseIdentifier: JYPictureCellReuseIdentifier)
        
        // 设置layout 属性 间距均为 10
        pictureLayout.minimumInteritemSpacing = 5
        pictureLayout.minimumLineSpacing = 5
        
    }
    
    
    // 根据模型和缓存图片来计算 pictureView 所占大小
    /**
    0. 没有图片，返回zero
    1. 单图会按照图片等比例显示
    2. 多图的图片大小固定
    3. 多图如果是4张，会按照 2 * 2 显示
    4. 多图其他数量，按照 3 * 3 九宫格显示
    */
    private func calcPictureViewSize(status: Status) -> (viewSize : CGSize , itemSize : CGSize) {
        // 多张图片时的固定大小和间距 以及多图 的行数
        let itemSize = CGSize(width: 90, height: 90)
        let margin: CGFloat = 5
        let rowCount = 3
        
        // 0.获取图片数量 如果为空就是 0
        let count = status.picURLs?.count ?? 0
  
        if count == 0 {
            return (CGSizeZero , CGSize(width: 0.1, height: 0.1))
        }
        
        // 1.一张图 就返回图片大小
        if count == 1 {
            // 从缓存拿到图片并创建image 保存
            let key = status.picURLs!.first?.absoluteString
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            // 判断图片宽度 
            let swidth = UIScreen.mainScreen().bounds.size.width * 0.8 as CGFloat
            if image.size.width <= swidth {
                return (image.size , image.size)
            }
            
            // 图片过宽 修改
            let th = image.size.height / image.size.width * swidth
            return(CGSize(width: swidth, height: th) , CGSize(width: swidth, height: th))
        }
        
        // 2. 4张图
        if count == 4 {
            let w = itemSize.width * 2 + margin
            return (CGSize(width: w, height: w) , itemSize)
        }
        
        // 3. 多张图 计算行列
        let row = (count - 1) / rowCount + 1
        let w = itemSize.width * CGFloat(rowCount) + CGFloat(rowCount - 1) * margin
        let h = itemSize.height * CGFloat(row) + CGFloat(row - 1) * margin
        return (CGSize(width: w, height: h) , itemSize)
    }

    // MARK: -添加视图和约束
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        addSubview(iconView)
        addSubview(memberIconView)
        addSubview(nameLabel)
        addSubview(vipIconView)
        addSubview(timeLabel)
        addSubview(sourceLabel)
        addSubview(contentLabel)
        addSubview(footerView)
        footerView.backgroundColor = UIColor(white: 0.95, alpha: 1)
        
        // 添加并设置 pictureView
        addSubview(pictureView)
        preparePictureView()
        pictureView.backgroundColor = UIColor.clearColor()
        
        let xyjg = 12.0 as CGFloat
        iconView.ff_edgesView(UIedgeView().top(self, c: xyjg).left(self, c: xyjg).size(35, h: 35))
        
        memberIconView.ff_edgesView(UIedgeView().left(iconView, c: -12).top(iconView, c: -12))
        
        nameLabel.ff_edgesView(UIedgeView().top(self, c: xyjg).left(iconView, c: xyjg))
        
        vipIconView.ff_edgesView(UIedgeView().top(self, c: xyjg).left(nameLabel, c: xyjg))
        
        timeLabel.ff_edgesView(UIedgeView().left(iconView , c:xyjg).bottom(iconView, c: 0, a: NSLayoutAttribute.Bottom))
        
        sourceLabel.ff_edgesView(UIedgeView().left(timeLabel , c:xyjg).bottom(timeLabel, c: 0, a: NSLayoutAttribute.Bottom))
        
        contentLabel.ff_edgesView(UIedgeView().left(self, c: xyjg).right(self, c: 4).top(iconView, c: xyjg))
        

         // 底部View
        footerView.ff_edgesView(UIedgeView().top(pictureView, c: xyjg).left(self, c: 0).right(self, c: 0).height(44))

    }

    // 表示不能用 sb  xib 创建 要么纯代码 要么 sb
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var iconView = UIImageView()
    lazy var nameLabel = UILabel(color: UIColor.darkGrayColor(), fontSize: 14)
    lazy var memberIconView: UIImageView = UIImageView(image: UIImage(named: "avatar_grassroot"))
    lazy var vipIconView : UIImageView = UIImageView(image: UIImage(named: "common_icon_membership_level3"))
    lazy var timeLabel = UILabel(color: UIColor.orangeColor(), fontSize: 10)
    lazy var sourceLabel = UILabel(color: UIColor.darkGrayColor(), fontSize: 10)
    lazy var contentLabel = UILabel(color: UIColor.darkGrayColor(), fontSize: 15, mutiLines: true)
    
    // 图像视图 UICollectionView 先定义 UICollectionViewFlowLayout
    lazy var pictureLayout = UICollectionViewFlowLayout()
    lazy var pictureView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: self.pictureLayout)
    
    // 底部视图but
     lazy var footerView : StatusFooterView = StatusFooterView()
    
    // 转发微博文字
     lazy var forwardLabel = UILabel(color: UIColor.darkGrayColor(), fontSize: 14 ,  mutiLines: true )
    
}

// MARK: - UICollectionView 的 cell
private class StatusPicturCell : UICollectionViewCell {
    /// 传入图像地址 显示
    var imageURL : NSURL? {
        didSet{
            // 设置图片
            iconView.sd_setImageWithURL(imageURL)
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(iconView)
        // 设置图片为等比例填充 ， 一定要裁剪图片 sb 无需
        iconView.contentMode = UIViewContentMode.ScaleAspectFill
        iconView.clipsToBounds = true
        
        iconView.ff_edgesView(UIedgeView().more(tlbr: ff_tlbr.all, v: self))
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 懒加载图片
    lazy var iconView = UIImageView()
    
}

// MARK: - 底部的butView
 class StatusFooterView: UIView {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        addSubview(forwardBtn)
        addSubview(commentBtn)
        addSubview(likeBtn)
    
        // 布局，水平平铺
        ff_HorizontalTile([forwardBtn, commentBtn, likeBtn], insets: UIEdgeInsetsZero)
    }
    
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    
    lazy var forwardBtn: UIButton = UIButton(title: "转发", imageName: "timeline_icon_retweet", fontSize: 12)
    lazy var commentBtn: UIButton = UIButton(title: "评论", imageName: "timeline_icon_comment", fontSize: 12)
    lazy var likeBtn: UIButton = UIButton(title: "点赞", imageName: "timeline_icon_unlike", fontSize: 12)
}

